package com.actionsoft.bpms.api;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONObject;
import com.alipay.remoting.util.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class ApiUtil {

    /**
    *@Author:JF
    *@Description:通过接口标识调用接口
    *@Date:2023/8/30 9:58
    *@parm:  * @param null
    */
    public static String callApiInterface(String url,Map params){
        if(StringUtils.isBlank(url)){
            throw new ApiException("传入的url标识不能为空！");
        }
        String response=null;
        ProcessInstance process = SDK.getProcessAPI().createBOProcessInstance("obj_d778147f5b9741138b427effafce0753", "admin", "调用接口日志");
        BO logBo=new BO();
        logBo.set("TO_DO_SYSTEM_ID","zjtrust_data");
        logBo.set("INTERFACE_NAME","url");
        logBo.set("INTERFACE_PARAMETER", JSONObject.toJSONString(params));
        logBo.set("CALL_METHOD",url);
        try {
            BO configBo = SDK.getBOAPI().query("BO_PS_MIDDLE_INTERFACE_PARAM").addQuery("INTERFACE_URL=", url).detail();
            if(null==configBo){
                throw new ApiException("中台接口参数配置表没有维护相关数据！");
            }
            String appKey = configBo.getString("APP_KEY");
            String apiToken = configBo.getString("API_TOKEN");
            String interfaceDomain = configBo.getString("INTERFACE_DOMAIN");
            String interfaceUrl = configBo.getString("INTERFACE_URL");
            String interfaceName = configBo.getString("INTERFACE_NAME");
            logBo.set("INTERFACE_NAME",interfaceName);
            String urlPath = interfaceDomain + interfaceUrl;
            Map header = new HashMap();
            header.put("apiToken", apiToken);
            header.put("appKey", appKey);
            header.put("version", "v2");
            long start = System.currentTimeMillis();
             response = sendGetHeader(urlPath, params, header);
            long end = System.currentTimeMillis();
            long callTime=end-start;
            logBo.set("AGING",callTime+"ms");
            logBo.set("SUCCESS_OR_FAILURE","1");
            logBo.set("NOTE",response.length()>2000?response.substring(0,1999):response);
        }catch(Exception e){
            logBo.set("SUCCESS_OR_FAILURE","0");
            logBo.set("NOTE",e.getMessage().length()>2000?e.getMessage().substring(0,1999):e.getMessage());
        }
        SDK.getBOAPI().create("BO_EU_INTERFACE_LOG",logBo,process.getId(),"admin");
        return response;
    }




    public static String sendGetHeader(String urltxt, Map params, Map header)
    {
        try{
            //提交地址和属性，一个以上的属性用&隔开
            URL url=new URL(urltxt + "?" + map2urlparams(params));


            HttpURLConnection conn = setUrlHeader(header, url);
            //设置超时时间，单位是秒
            conn.setConnectTimeout(5000);
            //访问提交方式
            conn.setRequestMethod("GET");
            conn.connect();
            //把输入流通过InputStreamReader将其转换为字符流
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            //把字符串提取出来
            String result = reader.readLine();
            return result;
        }catch(Exception ex){
            return "";
        }
    }


    private static String map2urlparams(Map<String, String> params) {
        String urlparams = "";
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if(urlparams.equals("") == false) urlparams += "&";
            urlparams += entry.getKey() + "=" + entry.getValue();
        }
        return urlparams;
    }


    private static HttpURLConnection setUrlHeader(Map<String,String> header,URL url) throws IOException {
        HttpURLConnection client=(HttpURLConnection)url.openConnection();
        if(CollectionUtils.isEmpty(header)){
            return client;
        }
        for(Map.Entry<String,String> head:header.entrySet()){
            client.setRequestProperty(head.getKey(),head.getValue());
        }

        return client;
    }
}
